<?php
/**
 *
 */
class Yz_Action_UpdateItem
    extends Yz_Action_Update
{

    /**
     *  Update requires at least one field/value
     *  @var Item
     */
    protected $values;


    /************************************
     *          Public methods          *
     ************************************/

    /**
     *  @param mixed $item
     *  @return this
     */
    public function setItem(Yz_Item_Interface $item)
    {
        if (! $item->id)
            throw ValueError::_new_();
        $this->values = $item;
        // prevent the action instance from returning results after changing parameters
        $this->count = null;
        return $this;
    }

    /***************************************
     *          Protected methods          *
     ***************************************/

    /** Verify any arguments before building query
     *      Ensure that an item has been designated to update
     *  @return this
     */
    protected function verifyArguments()
    {
        debug();
        if (! $this->values)
            // assert that if values are non-empty, the fields have been set, too (@see identifyValues)
           throw StateError::_new_();
        return $this;
    }


    /**
     *  Common UPDATE statement creator:
     *      the common part of statement
     *  @return Yz_SQL_Statement_Update
     */
    protected function buildStatement()
    {
        debug();
        return parent::buildStatement()
            ->where(key($this->tables) . ".id=:id")
        ;
    }

    /**
     *  Apply the arguments to the SQL statement
     *      Setup limit to avoid occasional selection of all rows
     *  @param Yz_SQL_Statement $sql
     *  @return this
     */
    protected function applyArguments(Yz_SQL_Statement $sql)
    {
        debug();
        $values = $this->values->toArray();
        foreach ($this->references as $refField)
            if (isset($values[$refField])) {
                assert("\$values['{$refField}'] instanceof Yz_Item_Interface");
                $values[$refField] = $values[$refField]->id;
            }
            // otherwise the value is null
        $sql
            ->bindArray($values)
        ;
        return $this;
    }

}
